package com.enba.mallapi.manager;

import cn.hutool.captcha.GifCaptcha;
import com.enba.boot.redis.RedisOperator;
import com.enba.mallapi.enums.CaptchaSceneEnum;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Component;

@Component
public class CaptchaManager {
  private final RedisOperator redisOperator;

  public CaptchaManager(RedisOperator redisOperator) {
    this.redisOperator = redisOperator;
  }

  // 返回验证码图片base64
  public Map<String, String> loginCaptcha() {
    return captcha(CaptchaSceneEnum.LOGIN_CAPTCHA, 130, 48, 4, 15);
  }

  /**
   * @param width 验证码宽度
   * @param height 验证码高度
   * @param codeCount 验证码个数
   * @param interfereCount 验证码干扰元素个数
   */
  public Map<String, String> captcha(
      CaptchaSceneEnum captchaSceneEnum, int width, int height, int codeCount, int interfereCount) {
    GifCaptcha gifCaptcha = new GifCaptcha(width, height, codeCount, interfereCount);

    // 验证码缓存
    String key = UUID.randomUUID().toString();
    String code = gifCaptcha.getCode();
    redisOperator.set(captchaSceneEnum.getRedisFullKey(key), code, 60);

    Map<String, String> result = new HashMap<>();
    result.put("key", key);
    result.put("image", gifCaptcha.getImageBase64Data());
    return result;
  }
}
